﻿using System.Composition;
using System.Diagnostics;
using System.Security.AccessControl;
using System.Text.Json;
using System.Text.Json.Nodes;
using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using ExchangeClient.ESB.Model;
using RestSharp;

namespace ExchangeClient.SAP
{
    [Export(typeof(IExchangeClient))]
    [ExportMetadata(YdConstants.ID, "Esb")]
    public class ESBClient : RestExchangeClientBase<ESBSetting>
    {
        public override bool VerifySignature(RequestData request)
        {
            return true;
        }
        protected override string GetAccessToken()
        {
            return "ok";
        }
        protected virtual RestResponse<JsonObject> Get1(string url)
        {
            var client = new RestClient(url);
            Logger.Info($"ESB开始 Get请求，URL: {url}");
            var request = new RestRequest(url, Method.Get);
            request.AddHeader("VerifyCode", Setting.FlowVerifyCode);
            var response = client.Execute<JsonObject>(request);
            Logger.Info($"ESB结束 Get请求，Resp: {response.Content}");
            Logger.Info($"ESB结束 Get请求，URL: {url}");
            HandleHttpError(response);
            return response;
        }
        protected virtual RestResponse<JsonObject> Post1(string url, string data, bool withToken = true, WebContentType contentType = WebContentType.Json)
        {
            JsonNode sendData = JsonNode.Parse(data, new JsonNodeOptions() { PropertyNameCaseInsensitive=true });
            var client = new RestClient(url);
            Logger.Info($"ESB开始 Post请求，URL: {url}");
            var request = new RestRequest(url, Method.Post);
            request.AddHeader("Content-Type", "application/json; charset=utf-8");
            request.AddParameter("application/json", sendData, ParameterType.RequestBody);
            request.AddHeader("VerifyCode", Setting.FlowVerifyCode);
            var response = client.Execute<JsonObject>(request);
            Logger.Info($"ESB结束 Post请求，Resp: {response.Content}");
            HandleHttpError(response);
            return response;
        }

        public override JsonObject PushProcess(ExchangeClient.Abstractions.Model.Process process)
        {
            var data =process.ExtraData;
            var url = Setting.StartProcessUrl;
            var systemUrl = data["systemAppUrl"]?.ToString();
            if (systemUrl.IndexOf("?") > 0) {
                systemUrl = systemUrl + "&";
            }
            else
            {
                systemUrl = systemUrl + "?";
            }
            systemUrl = systemUrl + "includeExpired=1&apptype=FeiShuAsset&corpid=2ca5ee4b42cf575e&appId=cli_9e38d55c6136100d&product=ASSET";
            var requestData = new
            {
                systemUrl = systemUrl,
                systemAppUrl = systemUrl,
                sourceSystem = Setting.SourceSystem,
                formCode = data["formCode"],
                billNo = process.SerialNo,
                operateUserId = process.UserId,
                processVariables = new
                {
                    applyUserId = process.UserId,
                    makerId = "",
                    applyOrgCode = "",
                    applyDeptCode = "",
                    suggestion = "",
                    compendium = data["formCode"] + "流程申请单",
                    applyPartOrgCode = "",
                    applyPartDeptCode = "",
                    applyCompanyCode = "",
                    expressionVariables = data["extraModel"]
                }


            };
            string jsonString = JsonSerializer.Serialize(requestData);
            Logger.Info("ESB发送数据："+jsonString);
            var response = Post1(url , jsonString);
            var result = JsonSerializer.Deserialize<StartFlowResponse>(response.Content!);
            JsonObject responseJson = new JsonObject();
            responseJson.Add("code", result.code);
            responseJson.Add("message", result.message);
            responseJson.Add("result", result.result);
            return responseJson;
        }
        public override JsonObject GetData(JsonObject data)
        {
            var url = Setting.GetProcessInstanceAuditLog;
            var sendData = new
            {
                procInstId = data["procInstId"],
                billNo = data["billNo"],
                sourceSystem = Setting.SourceSystem,
                operateUserId = data["operateUserId"]
            };
            string jsonString = JsonSerializer.Serialize(sendData);
            Logger.Info("ESB发送数据：" + jsonString);
            var response = Post1( url, jsonString);
            
            var result = JsonSerializer.Deserialize<GetLogResponse>(response.Content!);
            JsonObject responseJson = new JsonObject();
            responseJson.Add("code", result.code);
            responseJson.Add("message", result.message);
            responseJson.Add("result",JsonNode.Parse (JsonSerializer.Serialize(result.result)));
            return responseJson;
        }

        public override bool AddNewCustomizedFormData(CustomizedFormData form) {
            var url = Setting.FreeUpBudget;
            var sendData = new
            {
                BUDGET_TYPE="5",
                YEAR=DateTime.Parse(form.Data["Date"].ToString()).ToString("yyyy"),
                MONTH = DateTime.Parse(form.Data["Date"].ToString()).ToString("MM").TrimStart('0'),
                BUSINESS_ID=form.Data["FKApplicationNo"],
                DOC_TYPE="14",
                ZCHECK="",
                BUDGET_DEPARTMENT=form.Data["CenterCode"].ToString(),
                BUDGET_ACCOUNT=form.Data["FeeSubclass"].ToString(),
                AMT=form.Data["Amount"].ToString()
            };
                string jsonString = JsonSerializer.Serialize(sendData);
            Logger.Info("释放预算请求参数：" + jsonString);
             var response = Post1(url, jsonString);
            var result = JsonSerializer.Deserialize<FreeUpBudgetResponse>(response.Content!);
            var formId = UserDefines.First(x => x.Name == "释放预算");
            var status = ExtendFields.First(x => x.ObjectType == 54 && x.Name == "返回状态");
            var message = ExtendFields.First(x => x.ObjectType == 54 && x.Name == "返回消息");
            JsonObject extra = new JsonObject
            {
                [status.FieldId] = result.code,
                [message.FieldId] = result.message

            };
            CustomerExecuteCallback(formId.Id.ToString(), form.Data["SerialNo"].ToString(), 54, extra);
            return true;
        }

        private void CustomerExecuteCallback(string formId, string serialNo, int sourceType, JsonObject extra)
        {
            Thread.Sleep(10000);
            if (Callback != null)
            {
                Logger.Info("callback来了");
                Callback(new CallbackData(CallbackDataType.CustomizedForm, formId, serialNo) { ObjectType = sourceType, ExtraData = extra });
            }

            Logger.Info("CallbackDataType.CustomizedForm: formid:" + formId + ",serialNo：" + serialNo + ",ObjectType:" + sourceType + "");
        }
    }
}